#!/bin/bash

# 启动所有必要的服务

echo "=========================================="
echo "启动 GeoGebra 完整服务套件"
echo "=========================================="

# 检查是否在项目根目录
if [ ! -f "fastapi_app.py" ] || [ ! -d "services" ]; then
    echo "错误: 请从项目根目录执行此脚本"
    echo "正确用法: ./deploy/start_all_services.sh"
    echo "当前目录: $(pwd)"
    exit 1
fi

# 检查并激活虚拟环境
if [ -d "venv" ]; then
    echo "发现虚拟环境，正在激活..."
    source venv/bin/activate
    PYTHON_CMD="python"
elif [ -d ".venv" ]; then
    echo "发现虚拟环境，正在激活..."
    source .venv/bin/activate
    PYTHON_CMD="python"
else
    # 检查Python环境
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
        echo "使用 python3 命令"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
        echo "使用 python 命令"
    else
        echo "错误: 未找到Python环境"
        echo "请确保已安装 Python 3.8+ 或激活虚拟环境"
        exit 1
    fi
fi

echo "Python版本: $($PYTHON_CMD --version)"

# 检查依赖
echo "检查依赖..."
$PYTHON_CMD -c "import fastapi, uvicorn" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "错误: 缺少必要依赖"
    echo "请运行以下命令安装依赖:"
    echo "  $PYTHON_CMD -m pip install -r requirements_full.txt"
    exit 1
fi

# 设置环境变量
export PYTHONPATH="${PYTHONPATH}:$(pwd)"

# 创建日志目录
mkdir -p logs

echo "=========================================="
echo "启动服务..."
echo "=========================================="

# 存储启动结果
RUNNING_SERVICES=()
STARTED_SERVICES=()
FAILED_SERVICES=()

# 检查端口是否已被占用的函数
check_port_occupied() {
    local port=$1
    lsof -i :$port >/dev/null 2>&1
}

# 启动单个服务的函数
start_service() {
    local service_name=$1
    local port=$2
    local command=$3
    local log_file=$4
    
    echo "检查 $service_name (端口 $port)..."
    
    if check_port_occupied $port; then
        echo "⚠️ $service_name 已在运行 (端口 $port 被占用)"
        RUNNING_SERVICES+=("$service_name")
        return 0
    fi
    
    echo "启动 $service_name 在端口 $port..."
    # 使用nohup启动服务
    nohup $command > $log_file 2>&1 &
    local pid=$!
    
    # 等待服务启动
    echo "等待服务启动..."
    sleep 5
    
    # 检查端口是否被占用（确认服务真正启动）
    if check_port_occupied $port; then
        echo "✓ $service_name 启动成功 (PID: $pid)"
        STARTED_SERVICES+=("$service_name")
        return 0
    else
        echo "✗ $service_name 启动失败 (端口未被占用，请检查日志: $log_file)"
        FAILED_SERVICES+=("$service_name")
        return 1
    fi
}

# 启动各个服务
start_service "元素提取API" 8002 \
    "$PYTHON_CMD -m uvicorn llm_apis.apis.ds_element_extraction_api:app --host 0.0.0.0 --port 8002 --log-level info" \
    "logs/element_api.log"

start_service "对话服务V2" 8001 \
    "$PYTHON_CMD -m uvicorn services.conversation_service_v2:app --host 0.0.0.0 --port 8001 --log-level info --timeout-keep-alive 0 --timeout-graceful-shutdown 0" \
    "logs/conversation_v2.log"

start_service "原始FastAPI服务" 8080 \
    "$PYTHON_CMD -m uvicorn fastapi_app:app --host 0.0.0.0 --port 8080 --log-level info" \
    "logs/fastapi_app.log"

# 输出启动结果总结
echo "=========================================="
echo "服务启动结果总结："
echo "=========================================="

if [ ${#RUNNING_SERVICES[@]} -gt 0 ]; then
    echo "已运行的服务: ${RUNNING_SERVICES[*]}"
fi

if [ ${#STARTED_SERVICES[@]} -gt 0 ]; then
    echo "新启动的服务: ${STARTED_SERVICES[*]}"
fi

if [ ${#FAILED_SERVICES[@]} -gt 0 ]; then
    echo "启动失败的服务: ${FAILED_SERVICES[*]}"
fi

# 检查是否有任何服务在运行
TOTAL_RUNNING=$((${#RUNNING_SERVICES[@]} + ${#STARTED_SERVICES[@]}))
if [ $TOTAL_RUNNING -eq 0 ]; then
    echo "❌ 没有任何服务在运行"
    exit 1
fi

echo "=========================================="
echo "服务信息："
echo "=========================================="
echo "服务地址："
if check_port_occupied 8080; then
    echo "- 原始FastAPI服务: http://localhost:8080"
fi
if check_port_occupied 8001; then
    echo "- 对话服务V2: http://localhost:8001/api/v2/chat"
fi
if check_port_occupied 8002; then
    echo "- 元素提取API: http://localhost:8002/extract_elements"
fi
echo ""
echo "健康检查："
if check_port_occupied 8080; then
    echo "- curl http://localhost:8080/health"
fi
if check_port_occupied 8001; then
    echo "- curl http://localhost:8001/health"
fi
if check_port_occupied 8002; then
    echo "- curl http://localhost:8002/docs"
fi
echo ""
echo "日志文件："
echo "- 原始FastAPI: logs/fastapi_app.log"
echo "- 对话服务V2: logs/conversation_v2.log"
echo "- 元素提取API: logs/element_api.log"
echo ""
echo "服务已在后台运行，使用 './deploy.sh stop' 可以停止所有服务"
echo "使用 './deploy.sh status' 可以检查服务状态"
echo "=========================================="

echo "✅ 服务启动完成，返回命令行" 